class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> ans = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        int n = 1, m = 0;   //n 记录当前节点个数，m作为除数
        double temp = 0;
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode current = queue.poll();
            n--;
            m++;
            temp += current.val;

            if(current.left != null) {
                queue.offer(current.left);
            }

            if(current.right != null) {
                queue.offer(current.right);
            }

            if(n == 0) {
                n = queue.size();
                ans.add(temp / m);
                temp = m = 0;
            }
        }

        return ans;
    }
}